
#include "es_spi.h"

void ES_SPI_Init()
{
	SPI_Init(SPI_FIRSTBIT_MSB,
		SPI_BAUDRATEPRESCALER_32,
		SPI_MODE_MASTER,
		SPI_CLOCKPOLARITY_LOW,
		SPI_CLOCKPHASE_1EDGE,
		SPI_DATADIRECTION_2LINES_FULLDUPLEX,
		SPI_NSS_SOFT,
		(uint8_t)0x07);


	SPI_Cmd(ENABLE);


}



 u8 SPI_WriteRead(u8 byte)
{
	while (SPI_GetFlagStatus(SPI_FLAG_TXE) == RESET);
	
	SPI_SendData(byte);

	while (SPI_GetFlagStatus(SPI_FLAG_RXNE) == RESET);

	return SPI_ReceiveData();
}



 u8 SPI_WriteBuf(u8 reg, u8 * buf, u8 len)
{
	u8 status;
	int i = 0;

	status = SPI_WriteRead(reg);

	for (; i < len; i++)
	{
		SPI_WriteRead(buf[i]);
	}

	return status;
}



 u8 SPI_WriteReg(u8 reg, u8 data)
{
	u8 val;

	val = SPI_WriteRead(reg);
	
	SPI_WriteRead(data);

	return val;
}



 u8 SPI_ReadBuf(u8 reg, u8 * buf, u8 len)
{
	u8 status;
	int i = 0;

	status = SPI_WriteRead(reg);

	for (; i < len; i++)
	{
		buf[i] = SPI_WriteRead(0xFF);
	}

	return status;
}



 u8 SPI_ReadReg(u8 reg)
{
	u8 data;

	SPI_WriteRead(reg);
	
	data = SPI_WriteRead(0xFF);

	return data;
}